﻿#region Imports
using System;
using System.Globalization;
using System.Windows.Data;
using CommonUtilities.Util;
#endregion

namespace CommonUtilities.Converters
{
    /// <summary>
    /// Facilitates conversion between <code>System.Int32</code> value and its padded equivalent
    /// </summary>
    public class NumberPaddingConverter : IValueConverter
    {
        #region IValueConverter Members
        /// <summary>
        /// Converts a <code>System.Int32</code> value to its padded equivalent
        /// </summary>
        /// <param name="value">A <code>System.Int32</code> to be padded</param>
        /// <param name="targetType"><code>System.Int32</code></param>
        /// <param name="parameter">Padding length as <code>System.Int32</code></param>
        /// <param name="culture">UI culture of thread</param>
        /// <returns>Padded equivalent of <code>System.Int32</code> value</returns>
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string source = Utilities.ExtractConverterInputs<string>(value, "");
            int paddingLength = Utilities.ExtractConverterInputs<int>(parameter, 0, (i) => { return i < 0; });

            return source.PadLeft(paddingLength, '0');
        }

        /// <summary>
        /// Converts a padded <code>System.Int32</code> value to its trimmed equivalent
        /// </summary>
        /// <param name="value">A padded <code>System.Int32</code> to be trimmed</param>
        /// <param name="targetType"><code>System.Int32</code></param>
        /// <param name="parameter">Padding length as <code>System.Int32</code></param>
        /// <param name="culture">UI culture of thread</param>
        /// <returns>Trimmed equivalent of a padded <code>System.Int32</code> value</returns>
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return Utilities.ExtractConverterInputs<string>(value, "").Trim('0');
        }
        #endregion
    }
}
